package com.bdqn.t382.util.Interceptor;

import com.bdqn.t382.pojo.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class RoleIdInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute("user");

        if (user != null) {
            Long roleId = user.getRoleId();
//            String requestUrl = request.getRequestURI();
            // 判断角色 ID 是否为 1，只有角色 ID 为 1 的用户可以访问查看数据的页面
            if (roleId == 1) {
                // 允许访问
                return true;
            } else {
                // 角色 ID 不为 1，不允许访问，重定向到错误页面
                response.sendRedirect(request.getContextPath() + "/error.jsp?msg=noPermission");
                return false;
            }
        } else {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false;
        }
    }
}
